package chatNI;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

/**
 * <b>Project ChatSystemG2 - INSA 4INFOA1 - 2013/2014</b>
 * <P>
 * <i>Package  chatNI</i> <br>
 * FileReceiver is the part of the chatNI that is related to the file reception. <br>
 * It extends Thread. 
 *
 * @author Sergio Gonzalez - Marie-Charlotte Bideaud
 */

public class FileReceiver extends Thread {

	final private int bufferSize = 1024;
	private String path;
	private ServerSocket servSocket;
	
	/**
	 * Constructor for the class FileReceiver
	 * 
	 * @param socket : ServerSocket
	 * @param fileName : String
	 * @param path : String
	 */
	public FileReceiver (ServerSocket socket, String fileName, String path) {
		this.servSocket = socket;
		String[] temp = fileName.split("\\\\");
		this.path = path+"\\"+temp[temp.length-1];
	}
	
	/**
	 * Method starting the thread
	 */
	public void run () {
		try { 
			initSocketTCP();
			JOptionPane.showMessageDialog(null,
					"Succesfully received.",
					"File receive",JOptionPane.PLAIN_MESSAGE);
		}	
		catch(IOException e) { 
			JOptionPane.showMessageDialog(null,
				    "An error occured during the file reception.",
				    "File reception error",JOptionPane.ERROR_MESSAGE); 
		}
	}
	
	/**
	 * File reception method
	 * 
	 * @throws IOException
	 */
	public void initSocketTCP () throws IOException {
		// to accept the TCP connection 
		Socket socket = servSocket.accept();
		
		// beginning of the reception
		InputStream is = socket.getInputStream();
		System.out.println("Receiver: "+ path);
		FileOutputStream newFile = new FileOutputStream(path);
		byte[] buffer = new byte[bufferSize];
		int len;
		while ( (len = is.read(buffer)) != -1 ){ 
			newFile.write(buffer,0,len);
		} 
		
		// end of the reception
		is.close();
		newFile.close(); 
		socket.close();
	}

	/**
	 * Getter for path
	 * 
	 * @return String
	 */
	public String getPath() {
		return path;
	}

	/**
	 * Setter for path
	 * 
	 * @param path : String
	 */
	public void setPath(String path) {
		this.path = path;
	}
	
}
